package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.*;
import com.bestv.search.common.model.uid.UID;
import com.bestv.search.common.service.InfoManager;
import com.bestv.search.common.service.SearchKeywordManager;
import com.bestv.search.common.util.CharUtil;
import com.bestv.search.common.util.ChineseCharToEn;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Michael Wang
 */
public class HitCommand {
    final static String filterFile = "filterWords.properties";
    private static PropertiesConfiguration config;
    private Logger logger = Logger.getLogger(HitCommand.class);
    private InfoManager infoManager;
    private SearchKeywordManager searchKeywordManager;

    public void saveSearchKeywordList(List<SearchKeywordWrapper> keywordList, String siteCode) {
        DataSourceKey key = DataSourceKeyUtil.convert(siteCode);
        List<SearchKeyword> keywords = transform(keywordList, key);
        if (keywords == null || keywords.size() == 0) {
            logger.info("No match keyword is found.");
            return;
        }
        searchKeywordManager.saveSearchKeywordList(key, keywords);
    }

    private List<SearchKeyword> transform(List<SearchKeywordWrapper> keywordList, DataSourceKey key) {
        List<SearchKeyword> keywords = new ArrayList<SearchKeyword>();
        String word, mediaCode, name, actors = "", directors = "";
        // 字母或数字
        String regix = "^\\w+$";
        Info info;
        for (SearchKeywordWrapper wrapper : keywordList) {
            SearchKeyword keyword = wrapper.getSearchKeyword();
            word = keyword.getKeyword();
            Pattern pattern = Pattern.compile(regix);
            // 匹配字母或数字时对keyword进行转换
            if (pattern.matcher(word).matches()) {
                mediaCode = wrapper.getMediaCode();
                List<Info> infoList = infoManager.getInfoByCode(key, mediaCode);
                if (infoList != null && infoList.size() > 0) {
                    info = infoList.get(0);
                    name = info.getName();
                    // program
                    if (info.getType().getId() == 3) {
                        actors = ((Program) info).getActors();
                        directors = ((Program) info).getDirectors();
                    }
                    // series
                    if (info.getType().getId() == 4) {
                        actors = ((Series) info).getActors();
                        directors = ((Series) info).getDirectors();
                    }
                    // schedule
                    if (info.getType().getId() == 5) {
                        actors = ((Schedule) info).getActors();
                        directors = ((Schedule) info).getDirectors();
                    }
                    name = name + " " + actors + " " + directors;
                    word = findRealKeywordInStr(name, word);
                    if (word == null || "".equals(word))
                        continue;
                    keyword.setKeyword(word);
                } else {
                    continue;
                }
            }
            keyword.setMediaCode(wrapper.getMediaCode());
            keyword.setId(new Long(UID.getUID(keyword)));
            if (shouldBeFilter(keyword.getKeyword())) {
                continue;
            }
            keywords.add(keyword);
        }
        return keywords;
    }

    private String findRealKeywordInStr(String name, String word) {
        String namePY = ChineseCharToEn.getAllFirstLetter(name);
        String nameNum;
        int offset;
        if (namePY.indexOf(word) != -1) {
            offset = namePY.indexOf(word);
            return name.substring(offset, offset + word.length());
        } else {
            nameNum = CharUtil.charToNum(namePY);
            if (nameNum.indexOf(word) != -1) {
                offset = nameNum.indexOf(word);
                return name.substring(offset, offset + word.length());
            }
        }
        return "";
    }

    private String[] getFilterWords() {
        try {
            config = new PropertiesConfiguration(filterFile);
            config.setReloadingStrategy(new FileChangedReloadingStrategy());
            String filterStr = config.getString("topNWordsFilter");
            return filterStr.split("_");
        } catch (Exception e) {
            logger.error("Gets filter words failed " + e.getMessage());
        }

        return null;
    }

    private boolean shouldBeFilter(String keyword) {
        String[] filterWords = getFilterWords();
        if (filterWords == null || keyword == null) {
            return false;
        }
        for (String filterWord : filterWords) {
            if (keyword.contains(filterWord)) {
                return true;
            }
        }
        return false;
    }

    public InfoManager getInfoManager() {
        return infoManager;
    }

    public void setInfoManager(InfoManager infoManager) {
        this.infoManager = infoManager;
    }

    public SearchKeywordManager getSearchKeywordManager() {
        return searchKeywordManager;
    }

    public void setSearchKeywordManager(SearchKeywordManager searchKeywordManager) {
        this.searchKeywordManager = searchKeywordManager;
    }
}
